package com.zhangye.test.api;

import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.zhangye.test.entity.EasyArResult;
import com.zhangye.test.entity.Results;
import com.zhangye.test.entity.SimilarResult;
import com.zhangye.test.model.Admin;
import com.zhangye.test.model.Category;
import com.zhangye.test.model.EasyAr;
import com.zhangye.test.model.Region;
import com.zhangye.test.service.CategoryService;
import com.zhangye.test.service.EasyArService;
import com.zhangye.test.service.QiniuService;
import com.zhangye.test.service.RegionService;
import com.zhangye.test.service.SafeSessionService;
import com.zhangye.test.util.AddressUtil;
import com.zhangye.test.util.HttpUtil;
import com.zhangye.test.util.JPushController;
import com.zhangye.test.util.cloudUtils;

/**
 * 上传图片
 * 作者： 张叶
 * 创建时间：2018年6月19日  下午4:03:49
 */
@Controller
@RequestMapping("api/arInsert")
public class ArInsertApi {

	@Autowired
	private QiniuService qiniuService;
	@Autowired
	private EasyArService easyArService;
	@Autowired
	private SafeSessionService safeSessionService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private RegionService regionService;
	

	/**
	 * 添加AR
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:39
	 */
	@ResponseBody
	@RequestMapping(value = "/insertType", method = RequestMethod.POST)
	public ApiResult insertType(
			@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl,
			String videoUrl,String name,String info,String lat,String lng,HttpServletRequest request,
			Long categoryId) {
		ApiResult result = new ApiResult();
		if(imageUrl != null && !"".equals(imageUrl) 
				&& videoUrl != null && !"".equals(videoUrl)
						&& name != null && !"".equals(name)
								&& info != null && !"".equals(info)
										&& lat != null && !"".equals(lat)
												&& lng != null && !"".equals(lng)){
			Admin admin = safeSessionService.getCurrent(request);
			if(admin != null && !"".equals(admin)){
				try{
					if(imageUrl.getBytes().length < 2097152){
						String image = qiniuService.upload("file", imageUrl.getOriginalFilename(),imageUrl.getBytes());
						EasyAr easyar = getEasyAr(name, info, lat, lng,
								categoryId, admin, image, videoUrl, null,1);
						try{
							int i = easyArService.insert(easyar);
							if(i > 0){
								JPushController.testSendPush("新作品已注册，请尽快审核");//推送
								result.msg.status = 0;
								result.msg.desc = "上传成功，审核后方可使用";	
							}else{
								result.msg.status = 1;
								result.msg.desc = "系统错误，上传失败";									
							}
						}catch (Exception e){
							result.msg.status = 1;
							result.msg.desc = "系统错误，上传失败";
						}
					}else{
						result.msg.status = 9;
						result.msg.desc = "请选择小于2MB的图片";
					}
				}catch (Exception e){
					result.msg.status = 4;
					result.msg.desc = "系统错误，上传文件失败";
				}
			}else{
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}
	
	
	
	
	/**
	 * 添加AR
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:39
	 */
	@ResponseBody
	@RequestMapping(value = "/insertVideo", method = RequestMethod.POST)
	public ApiResult insertVideo(
			@RequestParam(value = "videoUrl", required = false) MultipartFile videoUrl) {
		ApiResult result = new ApiResult();
		try {
			String video = qiniuService.upload("file", videoUrl.getOriginalFilename(),videoUrl.getBytes());
			result.data.put("videoUrl", video);
			result.msg.status = 0;
			result.msg.desc = "上传成功";
		} catch (Exception e) {
			result.msg.status = 1;
			result.msg.desc = "系统错误,上传失败";
		}
		return result;
	}
	
	
	/**
	 * 添加AR
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:39
	 */
	@ResponseBody
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public ApiResult insert(
			@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl,
			String videoUrl,String name,String info,
			String lat,String lng,HttpServletRequest request,
			Long categoryId) {
		ApiResult result = new ApiResult();

		if(imageUrl != null && !"".equals(imageUrl) 
				&& videoUrl != null && !"".equals(videoUrl)
						&& name != null && !"".equals(name)
								&& info != null && !"".equals(info)
										&& lat != null && !"".equals(lat)
												&& lng != null && !"".equals(lng)){
			Admin admin = safeSessionService.getCurrent(request);
			if(admin != null && !"".equals(admin)){
				try{
					if(imageUrl.getBytes().length < 2097152){
						String image = qiniuService.upload("file", imageUrl.getOriginalFilename(),imageUrl.getBytes());
						EasyArResult er = cloudUtils.addClouds(encode(imageUrl.getBytes()), name, 20, encode(videoUrl.getBytes()));
						if(er != null && !"".equals(er)){
							String status = er.getStatusCode();
							if(status.equals("0")){//添加成功，入库
								EasyAr easyar = getEasyAr(name, info, lat, lng,
										categoryId, admin, image, videoUrl, er,0);
								try{
									int i = easyArService.insert(easyar);
									if(i > 0){
										JPushController.testSendPush("新作品已注册，请尽快审核");//推送
										result.msg.status = 0;
										result.msg.desc = "上传成功，审核后方可使用";	
									}else{
										result.msg.status = 1;
										result.msg.desc = "系统错误，上传失败";									
									}
								}catch (Exception e){
									cloudUtils.removeClouds(easyar.getTargetId());
									result.msg.status = 7;
									result.msg.desc = "系统错误，上传失败";
								}
							}else if(status.equals("421")){
								result.msg.status = 9;
								result.msg.desc = "请选择小于2MB的图片";
							}else if(status.equals("419")){
								result.msg.status = 8;
								result.msg.desc = "已存在相似图片，请重新上传";
							}
						}else{
							result.msg.status = 7;
							result.msg.desc = "系统错误，上传失败";
						}
					}else{
						result.msg.status = 9;
						result.msg.desc = "请选择小于2MB的图片";
					}
				}catch (Exception e){
					result.msg.status = 4;
					result.msg.desc = "系统错误，上传失败";
				}
			}else{
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}
	
	
	/**
	 * 修改视频
	 * 作者： 张叶
	 * 创建时间：2018年8月28日  上午11:54:13
	 */
	@ResponseBody
	@RequestMapping(value = "/updateVideoUrl", method = RequestMethod.POST)
	public ApiResult updateVideoUrl(HttpServletRequest request,Long easyArId,
			@RequestParam(value = "videoUrl", required = false) MultipartFile videoUrl) {
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(admin != null && !"".equals(admin)){
			if(easyArId != null && !"".equals(easyArId)){
				String where = " and admin_id = " + admin.getId() + " and id = " + easyArId;
				List<EasyAr> list = easyArService.selectByWhere(where);
				if(list.size() == 1){
					try {
						int i = easyArService.updateVideoUrl(easyArId, videoUrl);
						if(i > 0){
							result.msg.status = 0;
							result.msg.desc = "修改成功";
						}else{
							result.msg.status = 1;
							result.msg.desc = "系统错误，修改失败";
						}
					} catch (Exception e) {
						result.msg.status = 1;
						result.msg.desc = "系统错误，修改失败";
					}
				}else{
					result.msg.status = 4;
					result.msg.desc = "系统错误，修改失败";
				}
			}else{
				result.msg.status = 3;
				result.msg.desc = "参数不能为空";
			}
		}else{
			result.msg.status = 2;
			result.msg.desc = "当前登录已失效，请重新登录";
		}
		return result;
	}	
	
	
	/**
	 * 修改图片
	 * 作者： 张叶
	 * 创建时间：2018年8月28日  上午11:52:40
	 */
	@ResponseBody
	@RequestMapping(value = "/updateImageUrl", method = RequestMethod.POST)
	public ApiResult updateImageUrl(HttpServletRequest request,Long easyArId,
			@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl) {
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(admin != null && !"".equals(admin)){
			if(easyArId != null && !"".equals(easyArId)){
				String where = " and admin_id = " + admin.getId() + " and id = " + easyArId;
				List<EasyAr> list = easyArService.selectByWhere(where);
				if(list.size() == 1){
					try {
						int i = easyArService.updateImageUrl(easyArId, imageUrl);
						if(i > 0){
							result.msg.status = 0;
							result.msg.desc = "修改成功";
						}else{
							result.msg.status = 1;
							result.msg.desc = "系统错误，修改失败";
						}
					} catch (Exception e) {
						result.msg.status = 1;
						result.msg.desc = "系统错误，修改失败";
					}
				}else{
					result.msg.status = 4;
					result.msg.desc = "系统错误，修改失败";
				}
			}else{
				result.msg.status = 3;
				result.msg.desc = "参数不能为空";
			}
		}else{
			result.msg.status = 2;
			result.msg.desc = "当前登录已失效，请重新登录";
		}
		return result;
	}	
	
	
	/**
	 * 修改
	 * 作者： 张叶
	 * 创建时间：2018年8月27日  上午9:18:29
	 */
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ApiResult update(HttpServletRequest request,Integer easyArId,
			String name,String info,Long categoryId) {
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(admin != null && !"".equals(admin)){
			String where = " and admin_id = " + admin.getId() + " and id = " + easyArId;
			List<EasyAr> list = easyArService.selectByWhere(where);
			if(list.size() == 1){
				EasyAr ea = list.get(0);
				if(name != null && !"".equals(name)){
					ea.setName(name);
				}
				if(info != null && !"".equals(info)){
					ea.setInfo(info);
				}
				if(categoryId != null && !"".equals(categoryId)){
					ea.setCategoryId(categoryId);
				}
				int i = easyArService.update(ea);
				if(i > 0){
					result.msg.status = 0;
					result.msg.desc = "修改成功";
				}else{
					result.msg.status = 1;
					result.msg.desc = "系统错误，修改失败";
				}
			}else{
				result.msg.status = 4;
				result.msg.desc = "系统错误，修改失败";
			}
		}else{
			result.msg.status = 2;
			result.msg.desc = "当前登录已失效，请重新登录";
		}
		return result;
	}	
	
	
	/**
	 * 添加AR
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:39
	 */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ApiResult add(
			@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl,
			@RequestParam(value = "videoUrl", required = false) MultipartFile videoUrl,
			String name,String info,String lat,String lng,HttpServletRequest request,
			Long categoryId) {
		ApiResult result = new ApiResult();

		if(imageUrl != null && !"".equals(imageUrl) 
				&& videoUrl != null && !"".equals(videoUrl)
						&& name != null && !"".equals(name)
								&& info != null && !"".equals(info)
										&& lat != null && !"".equals(lat)
												&& lng != null && !"".equals(lng)){
			Admin admin = safeSessionService.getCurrent(request);
			if(admin != null && !"".equals(admin)){
				try{
					if(imageUrl.getBytes().length < 2097152){
						String image = qiniuService.upload("file", imageUrl.getOriginalFilename(),imageUrl.getBytes());
						String video = qiniuService.upload("file", videoUrl.getOriginalFilename(),videoUrl.getBytes());
						EasyArResult er = cloudUtils.addClouds(encode(imageUrl.getBytes()), name, 20, encode(video.getBytes()));
						if(er != null && !"".equals(er)){
							String status = er.getStatusCode();
							if(status.equals("0")){//添加成功，入库
								EasyAr easyar = getEasyAr(name, info, lat, lng,
										categoryId, admin, image, video, er,0);
								try{
									int i = easyArService.insert(easyar);
									if(i > 0){
										JPushController.testSendPush("新作品已注册，请尽快审核");//推送
										result.msg.status = 0;
										result.msg.desc = "上传成功，审核后方可使用";	
									}else{
										result.msg.status = 1;
										result.msg.desc = "系统错误，上传失败";									
									}
								}catch (Exception e){
									cloudUtils.removeClouds(easyar.getTargetId());
									result.msg.status = 7;
									result.msg.desc = "系统错误，上传失败";
								}
							}else if(status.equals("421")){
								result.msg.status = 9;
								result.msg.desc = "请选择小于2MB的图片";
							}else if(status.equals("419")){
								result.msg.status = 8;
								result.msg.desc = "已存在相似图片，请重新上传";
							}
						}else{
							result.msg.status = 7;
							result.msg.desc = "系统错误，上传失败";
						}
					}else{
						result.msg.status = 9;
						result.msg.desc = "请选择小于2MB的图片";
					}
				}catch (Exception e){
					result.msg.status = 4;
					result.msg.desc = "系统错误，上传失败";
				}
			}else{
				result.msg.status = 2;
				result.msg.desc = "当前登录已失效，请重新登录";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}


	private EasyAr getEasyAr(String name, String info, String lat, String lng,
			Long categoryId, Admin admin, String image, String video,
			EasyArResult er,Integer type) {
		EasyAr easyar = new EasyAr();
		if(er != null && !"".equals(er)){
			easyar.setTargetId(er.getResult().getTargetId());
			easyar.setActive(er.getResult().getActive());
		}
		easyar.setImageUrl(image);
		easyar.setName(name);
		easyar.setVideoUrl(video);
		easyar.setAdminId(admin.getId());
		easyar.setCreateAt(new Date());
		String address = getAddress(lat, lng);
		easyar.setAddressLat(lat);
		easyar.setAddressLng(lng);
		easyar.setAddress(address);
		easyar.setInfo(info);
		easyar.setType(type);
		if(categoryId != null && !"".equals(categoryId)){
			Category category = categoryService.selectByPrimaryKey(categoryId);
			if(category != null && !"".equals(category)){
				easyar.setCategoryId(category.getId());
				easyar.setCategoryCode(category.getCode());
				easyar.setCategoryName(category.getName());
			}else{
				category = categoryService.selectByCode(categoryId + "");
				if(category != null && !"".equals(category)){
					easyar.setCategoryId(category.getId());
					easyar.setCategoryCode(category.getCode());
					easyar.setCategoryName(category.getName());
				}
			}
		}

		Region region = new Region();
		try{
			region = getRegionByLocation(String.format("%s,%s", lng, lat));
		}catch(Exception e){
			region = regionService.getRegionByCode("130101");
		}
		
		easyar.setRegionId(region.getId());
		easyar.setRegionCode(region.getCode());
		easyar.setRegionName(region.getTitle());
		return easyar;
	}
	

	/**
	 * 检查图片相似度
	 * 作者： 张叶
	 * 创建时间：2018年7月3日  下午3:35:20
	 */
	@ResponseBody
	@RequestMapping(value = "/checkSame", method = RequestMethod.POST)
	public ApiResult checkSame(@RequestParam(value = "imageUrl", required = false) MultipartFile imageUrl) {
		ApiResult result = new ApiResult();
		try {
			if(imageUrl.getBytes().length < 2097152){
				SimilarResult sr = cloudUtils.similarCloud(encode(imageUrl.getBytes()));
				if(sr != null && !"".equals(sr)){
					List<Results> list = sr.getSimilar().getResults();
					if(list.size() == 0){
						result.msg.status = 0;
						result.msg.desc = "暂无相似图片";
					}else{
						String a = sr.getSimilar().getResults().get(0).getTargetId();
						cloudUtils.getCloud(a);
						result.msg.status = 1;
						result.msg.desc = "已存在相似图片，请重新上传";
					}
				}else{
					result.msg.status = 3;
					result.msg.desc = "请选择小于2MB的图片";
				}
			}else{
				result.msg.status = 3;
				result.msg.desc = "请选择小于2MB的图片";
			}
		} catch (Exception e) {
			result.msg.status = 3;
			result.msg.desc = "请选择小于2MB的图片";
		}
		return result;
	}
	

	public static String encode(final byte[] bytes) {  
		return new String(Base64.encodeBase64(bytes));  
	}	

	
	/**
	 * 获取视频分类
	 * 作者： 张叶
	 * 创建时间：2018年8月27日  下午2:00:55
	 */
	@ResponseBody
	@RequestMapping(value = "/getCategory")
	public ApiResult getCategory() {
		ApiResult result = new ApiResult();
		String where = " and level = 1 and code != '29'";
		List<Category> list = categoryService.selectByWhere(where);
		if(list.size() > 0){
			result.data.put("categoryList", list);
			result.msg.status = 0;
			result.msg.desc = "获取成功";
		}else{
			result.msg.status = 1;
			result.msg.desc = "暂无数据";
		}
		return result;
	}


	
	public String getAddress(String lat, String lng) {
		String region = "";
		try {
			region = AddressUtil.getRegionByLocation(String.format("%s,%s", lng, lat));
		} catch (Exception e) {
			region = "河北省石家庄市";
		}
		return region;
	}

	/**
	 * 获取定位信息
	 * 作者： 张叶
	 * 创建时间：2016年11月17日  下午1:48:06
	 */
    public Region getRegionByLocation(String location) {
        List<Region> list = regionService.selectByWhere(" and status = 'on'");
        String key = "ff53d41333699e71213e01ed52a73761";
        String url = String.format("http://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s&poitype=&radius=&extensions=all&batch=false&roadlevel=", key, location);
        String content = HttpUtil.requestGet(url);
        JSONObject json = JSONObject.parseObject(content);
        Region region = null;
        if ("1".equalsIgnoreCase(json.getString("status"))) {//正常
            JSONObject a = json.getJSONObject("regeocode").getJSONObject("addressComponent");

            String district = a.getString("district");
            String adcode = a.getString("adcode");
            String address = json.getJSONObject("regeocode").getString("formatted_address");
            String city = a.getString("city");
            try {//匹配乡镇
                region = list.stream().filter(region1 -> region1.getName().contains(city)).findAny().get();
            } catch (NoSuchElementException e) {
            	
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (region == null) {//匹配城区
                try {
                    region = list.stream().filter(region1 -> 
                    region1.getName().contains(district)).findAny().get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (region == null) {//未匹配到
                region = new Region();
                region.setLevel(3);
                region.setCode(adcode);
                region.setName(district);
                region.setStatus("on");
                region.setTitle(district);
            }
            if (region.getLevel() == 4) {
                region = regionService.getRegionByCode(region.getCode().substring(0, 6));
            } else if (region.getLevel() == 3) {
            	region = regionService.getRegionByCode(region.getCode());
            } else if (region.getLevel() == 2) {
            	region = regionService.getRegionByCode(region.getCode() + "01");
            }
            region.setRemark(address);
        }
        return region;
    }

	
}
